<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Template;
use Illuminate\Http\Request;

class TemplateController extends Controller
{
    public function index()
    {
        $list = Template::paginate(15);

        return response()->json(['code' => 200, 'message' => '成功', 'data' => $list]);
    }

    public function show($id)
    {
        $res = Template::find($id);
        if (!$res) {
            return response()->json(['code' => 400, 'message' => '失败']);
        } else {
            return response()->json(['code' => 200, 'message' => '成功', 'data' => $res]);
        }
    }

    public function store(Request $request)
    {
        $title = $request->post('title');
        $content = $request->post('content');
        $tokens = $request->post('tokens');
        $remark = $request->post('remark');

        $save_data = [
            'title' => $title,
            'content' => $content,
            'tokens' => $tokens,
            'remark' => $remark,
        ];

        $save = Template::create($save_data);
        if (!$save) {
            return response()->json(['code' => 400, 'message' => '创建模板失败']);
        } else {
            return response()->json(['code' => 200, 'message' => '创建模板成功']);
        }
    }

    public function update(Request $request, $id)
    {
        $title = $request->post('title');
        $content = $request->post('content');
        $tokens = $request->post('tokens');
        $remark = $request->post('remark');

        $save_data = [
            'title' => $title,
            'content' => $content,
            'tokens' => $tokens,
            'remark' => $remark,
        ];

        $save = Template::where('id', $id)->update($save_data);
        if (!$save) {
            return response()->json(['code' => 400, 'message' => '编辑模板失败']);
        } else {
            return response()->json(['code' => 200, 'message' => '编辑模板成功']);
        }
    }

    public function destroy($id)
    {
        $save = Template::where('id', $id)->delete();
        if (!$save) {
            return response()->json(['code' => 400, 'message' => '删除模板失败']);
        } else {
            return response()->json(['code' => 200, 'message' => '删除模板成功']);
        }
    }

}
